package handlers

import (
	"context"
	"ourplansystem/server/ent"
	"ourplansystem/server/models"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
)

// CountdownHandler 倒计时处理器
type CountdownHandler struct {
	client *ent.Client
}

// NewCountdownHandler 创建倒计时处理器
func NewCountdownHandler(client *ent.Client) *CountdownHandler {
	return &CountdownHandler{client: client}
}

// CreateCountdownRequest 创建倒计时请求
type CreateCountdownRequest struct {
	Title       string `json:"title"`
	TargetDate  string `json:"target_date"` // 格式: 2006-01-02
	Description string `json:"description"`
	Type        string `json:"type"`
	CreatorID   int64  `json:"creator_id"`
}

// UpdateCountdownRequest 更新倒计时请求
type UpdateCountdownRequest struct {
	Title       string `json:"title"`
	TargetDate  string `json:"target_date"`
	Description string `json:"description"`
	Type        string `json:"type"`
}

// GetCountdowns 获取所有倒计时
func (h *CountdownHandler) GetCountdowns(c *fiber.Ctx) error {
	ctx := context.Background()
	countdowns, err := h.client.Countdown.Query().WithCreator().All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取倒计时列表失败")
	}

	return models.Success(c, countdowns)
}

// GetCountdown 获取单个倒计时
func (h *CountdownHandler) GetCountdown(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的倒计时ID")
	}

	countdown, err := h.client.Countdown.Get(ctx, id)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "倒计时不存在")
		}
		return models.InternalServerError(c, "获取倒计时失败")
	}

	return models.Success(c, countdown)
}

// CreateCountdown 创建倒计时
func (h *CountdownHandler) CreateCountdown(c *fiber.Ctx) error {
	ctx := context.Background()
	var req CreateCountdownRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.Title == "" {
		return models.BadRequest(c, "标题不能为空")
	}

	if req.CreatorID == 0 {
		return models.BadRequest(c, "创建者ID不能为空")
	}

	// 解析目标日期 - 支持多种格式
	var targetDate time.Time
	var err error

	// 尝试解析完整的日期时间格式 "2006-01-02 15:04:05"
	targetDate, err = time.Parse("2006-01-02 15:04:05", req.TargetDate)
	if err != nil {
		// 如果失败，尝试解析仅日期格式 "2006-01-02"
		targetDate, err = time.Parse("2006-01-02", req.TargetDate)
		if err != nil {
			return models.BadRequest(c, "目标日期格式错误，应为: 2006-01-02 或 2006-01-02 15:04:05")
		}
	}

	builder := h.client.Countdown.
		Create().
		SetTitle(req.Title).
		SetTargetDate(targetDate).
		SetCreatorID(req.CreatorID)

	if req.Description != "" {
		builder.SetDescription(req.Description)
	}

	if req.Type != "" {
		builder.SetType(req.Type)
	}

	countdown, err := builder.Save(ctx)
	if err != nil {
		return models.InternalServerError(c, "创建倒计时失败")
	}

	return models.SuccessWithMessage(c, "创建成功", countdown)
}

// UpdateCountdown 更新倒计时
func (h *CountdownHandler) UpdateCountdown(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的倒计时ID")
	}

	var req UpdateCountdownRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	builder := h.client.Countdown.UpdateOneID(id)

	if req.Title != "" {
		builder.SetTitle(req.Title)
	}

	if req.Description != "" {
		builder.SetDescription(req.Description)
	}

	if req.TargetDate != "" {
		// 尝试解析完整的日期时间格式 "2006-01-02 15:04:05"
		targetDate, err := time.Parse("2006-01-02 15:04:05", req.TargetDate)
		if err != nil {
			// 如果失败，尝试解析仅日期格式 "2006-01-02"
			targetDate, err = time.Parse("2006-01-02", req.TargetDate)
			if err != nil {
				return models.BadRequest(c, "目标日期格式错误，应为: 2006-01-02 或 2006-01-02 15:04:05")
			}
		}
		builder.SetTargetDate(targetDate)
	}

	if req.Type != "" {
		builder.SetType(req.Type)
	}

	countdown, err := builder.Save(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "倒计时不存在")
		}
		return models.InternalServerError(c, "更新倒计时失败")
	}

	return models.SuccessWithMessage(c, "更新成功", countdown)
}

// DeleteCountdown 删除倒计时
func (h *CountdownHandler) DeleteCountdown(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的倒计时ID")
	}

	err = h.client.Countdown.DeleteOneID(id).Exec(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "倒计时不存在")
		}
		return models.InternalServerError(c, "删除倒计时失败")
	}

	return models.SuccessWithMessage(c, "删除成功", nil)
}
